package com.xizi.forum.interceptor;

import com.xizi.forum.common.Constants;
import com.xizi.forum.common.ResultCode;
import com.xizi.forum.exception.ApplicationException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class LoginInterception implements HandlerInterceptor {

    @Value(value = "${xizi-forum.login.url}")
    private String defaultUrl;

//    @PostConstruct
//    public void init() {
//        System.out.println("登录跳转地址是：" + defaultUrl);
//    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute(Constants.USERINFO) != null){
            log.info("拦截失败！");
            return true;
        }
        log.info(defaultUrl);
        log.info("拦截成功！,session : {}",session);
        if(!defaultUrl.startsWith("/")){
            defaultUrl += "/";
        }

        response.sendRedirect(defaultUrl);
        throw new ApplicationException(ResultCode.FAILED_NOT_LOGIN);
    }
}
